package dhy.com.controller;
import dhy.com.exception.CustomExceptionType;
import dhy.com.result.AjaxResponse;
import dhy.com.service.ClawerService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
public class ClawerController
{
    @Resource
    private ClawerService clawerService;

   //开始爬取,获取用户输入需要爬取的图片关键字,和数据存放的文件名
    //从第几页开始爬取，爬取到第几页
    //还是从第几页开始爬取，一直到点击停止爬取的按钮为止
   @GetMapping("/start_clawer")
   public synchronized AjaxResponse startClawer(@RequestParam String keyWord,
                                   @RequestParam(required = false) String pageNum,
                                   @RequestParam(required = false)String endPageNum,
                                   @RequestParam(required = false)String cron,
                                   HttpServletRequest request)
   {
       //开启定时任务，并使用nio将爬取到的图片，放到指定主机的文件夹下面
       //将用户数据存入session中
       //获取session，如果不存在就创建
       HttpSession httpSession = request.getSession(true);
       httpSession.setAttribute("keyWord",keyWord);
       httpSession.setAttribute("pageNum",pageNum);
       httpSession.setAttribute("endPageNum",endPageNum);
       httpSession.setAttribute("cron",cron);
       //开始爬取
       clawerService.start();
       return AjaxResponse.success();
   }

    //停止爬取
    @GetMapping("/stop_clawer")
    public synchronized AjaxResponse stopClawer(HttpServletRequest request)
    {
        HttpSession session = request.getSession(false);
        if(session==null)
        {
            return AjaxResponse.error(CustomExceptionType.USER_INPUT_ERROR,"请先开始爬取");
        }
        clawerService.stopClawer(session);
        return AjaxResponse.success();
    }

    //继续爬取
//    @GetMapping("/continue_clawer")
//    public AjaxResponse continueClawer()
//    {
//        //TODO:待完善
//        return AjaxResponse.success();
//    }

    //查看正在运行的所有爬虫线程----显示的是正在工作的爬虫任务，当任务进入休息间隔的时候，不会显示
//    @GetMapping("/get_alive_clawer_list")
//    public AjaxResponse getAliveClawerList()
//    {
//        return AjaxResponse.success(clawerService.getAliveList());
//    }

    //查看所有爬虫线程
//    @GetMapping("/get_clawer_list")
//    public AjaxResponse getClawerList()
//    {
//        return AjaxResponse.success(clawerService.getClawerList());
//    }

    //下载爬取到的图片---压缩包形式
    @GetMapping("/download")
    public void downloadPics()
    {
           clawerService.downLoad();
    }

    //关闭页面
    @GetMapping("exit")
    public  AjaxResponse exit()
    {
        clawerService.exit();
        return AjaxResponse.success();
    }
}
